package adminlogcontroller

import (
	"context"
	"encoding/json"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/dao/adminlogdao"
	"vpn-management-server/src/model/adminlogmodel"
	"vpn-management-server/src/service/adminservice"
)

func GetAdminLogs(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	// 返回数据结构体内的字段全部导出（大写首字母）
	var resData = struct {
		AdminLogs []*adminlogmodel.AdminLog
		Count     int
	}{}
	if adminLogJson, ok := request.GetModel().(*adminlogmodel.AdminLogJson); ok {
		adminLogs := adminlogdao.GetAllAdminLogs(adminLogJson.PageSize, adminLogJson.PageNo, adminLogJson.BeginTime, adminLogJson.EndTime)
		count := adminlogdao.GetAdminLogsCount(adminLogJson.BeginTime, adminLogJson.EndTime)
		if len(adminLogs) == 0 {
			logger.Logger.Warn("admin log is empty")
		}
		resData.AdminLogs = adminLogs
		resData.Count = count
		data, _ := json.Marshal(resData)
		response.Code = code.SUCCESS
		response.Data = data
		logger.Logger.Infof("get admin logger info success\n")
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "Transform interface to AdminLogJson fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "transform interface to AdminLogJson fail"
	}
}
func GetAdminLogsByAdminID(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	var resData = struct {
		AdminLogs []*adminlogmodel.AdminLog
		Count     int
	}{}
	if adminLogIDJson, ok := request.GetModel().(*adminlogmodel.AdminLogIDJson); ok {
		// TODO 调用adminservice中的函数获取管理员名字
		admin, ok := adminservice.GetAdminByIdService(adminLogIDJson.AdminID)
		if admin == nil || !ok {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "get admin by id fail")
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "get admin by ID fail"
			return
		}
		adminLogs := adminlogdao.GetAdminLogsByAdminName(adminLogIDJson.PageSize, adminLogIDJson.PageNo, adminLogIDJson.BeginTime, adminLogIDJson.EndTime, admin.Name)
		count := adminlogdao.GetAdminLogsCountByAdminName(adminLogIDJson.BeginTime, adminLogIDJson.EndTime, admin.Name)
		if adminLogs == nil {
			logger.Logger.Warn("admin logger is empty")
			adminLogs = []*adminlogmodel.AdminLog{}
		}
		resData.AdminLogs = adminLogs
		resData.Count = count
		data, _ := json.Marshal(resData)
		response.Code = code.SUCCESS
		response.Data = data
		logger.Logger.Infof("get admin logger by admin ID info success\n")
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "Transform interface to AdminLogIDJson fail")
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "transform interface to adminLogIDJson fail"
	}
}
